#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    typedef ListNode Node;
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        Node* cur1 = l1, * cur2 = l2;
        Node* newhead, * newtail;
        newhead = newtail = new Node();
        int flag = 0;
        while (cur1 && cur2) {
            int n = ((cur1->val + cur2->val) + flag);

            Node* node = new Node(n % 10);
            flag = n / 10;

            newtail->next = node;
            newtail = node;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }

        while (cur1) {
            int n = cur1->val + flag;
            flag = n / 10;
            Node* node = new Node(n % 10);
            newtail->next = node;
            newtail = node;
            cur1 = cur1->next;
        }
        while (cur2) {
            int n = cur2->val + flag;
            flag = n / 10;
            Node* node = new Node(n % 10);
            newtail->next = node;
            newtail = node;
            cur2 = cur2->next;
        }
        if (cur1 == nullptr && cur2 == nullptr && flag) {
            Node* node = new Node(flag);
            newtail->next = node;
            newtail = node;
        }
        return newhead->next;
    }
};